<template>
  <div class="appointment-records-page">
    <van-nav-bar title="预约挂号记录" left-arrow @click-left="goBack" />
    
    <!-- 就诊人信息卡片 -->
    <div class="patient-card">
      <div class="patient-info">
        <div class="patient-name">
          <span class="name">{{ selectedPatient?.name || '请选择就诊人' }}</span>
          <van-tag v-if="selectedPatient?.relationship" type="primary">
            {{ selectedPatient.relationship }}
          </van-tag>
        </div>
        <div class="patient-card-number">
          {{ selectedPatient?.medicalCard ? maskCardNumber(selectedPatient.medicalCard) : '' }}
        </div>
      </div>
      <div class="switch-patient" @click="showPatientList = true">
        <van-icon name="arrow" />
        <span>切换就诊人</span>
      </div>
    </div>

    <!-- 时间筛选 -->
    <div class="filter-section">
      <van-button 
        :type="timeFilter === 'year' ? 'primary' : 'default'" 
        size="small"
        @click="timeFilter = 'year'"
      >
        近一年
      </van-button>
      <van-button 
        :type="timeFilter === 'custom' ? 'primary' : 'default'" 
        size="small"
        @click="showTimePicker = true"
      >
        选择时间 ▼
      </van-button>
    </div>

    <!-- 预约记录列表 -->
    <div class="appointment-records" v-if="selectedPatient">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadAppointmentRecords"
      >
        <div 
          v-for="record in appointmentRecords" 
          :key="record.appointmentId"
          class="appointment-record-card"
          @click="goToAppointmentDetails(record)"
        >
          <div class="record-info">
            <div class="department-doctor">
              {{ record.departmentName }} {{ record.attendingName }}
            </div>
            <div class="consultation-department">
              就诊科室 {{ record.department }}
            </div>
            <div class="consultation-time">
              就诊时间 {{ formatDateTime(record.outpatientTime) }}
            </div>
            <div class="patient-name">
              就诊人 {{ record.name }}
            </div>
          </div>
          <div class="status">
            <van-tag 
              :type="getStatusType(record)" 
              :color="getStatusColor(record)"
            >
              {{ getStatusText(record) }}
            </van-tag>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 就诊人选择弹窗 -->
    <van-popup v-model:show="showPatientList" position="bottom" round>
      <div class="patient-list-popup">
        <div class="popup-header">
          <h3>选择就诊人</h3>
          <van-icon name="cross" @click="showPatientList = false" />
        </div>
        <van-list>
          <van-cell
            v-for="patient in patients"
            :key="patient.patientId"
            :title="patient.name"
            :label="patient.relationship"
            :value="maskCardNumber(patient.medicalCard)"
            @click="selectPatient(patient)"
          />
        </van-list>
      </div>
    </van-popup>

    <!-- 时间选择弹窗 -->
    <van-popup v-model:show="showTimePicker" position="bottom" round>
      <van-datetime-picker
        v-model="selectedDate"
        type="date"
        title="选择日期"
        @confirm="onTimeConfirm"
        @cancel="showTimePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { api, type Patient, type AppointmentRecord } from '../../api'

const router = useRouter()

// 响应式数据
const patients = ref<Patient[]>([])
const selectedPatient = ref<Patient | null>(null)
const appointmentRecords = ref<AppointmentRecord[]>([])
const loading = ref(false)
const finished = ref(false)
const showPatientList = ref(false)
const showTimePicker = ref(false)
const timeFilter = ref<'year' | 'custom'>('year')
const selectedDate = ref(new Date())

// 计算属性
const maskCardNumber = (cardNumber: string) => {
  if (!cardNumber) return ''
  if (cardNumber.length <= 8) return cardNumber
  return cardNumber.substring(0, 3) + '*********' + cardNumber.substring(cardNumber.length - 4)
}

const formatDateTime = (dateTime: string) => {
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 获取状态文本
const getStatusText = (record: AppointmentRecord) => {
  if (record.reason && record.cancelTime) {
    return '已取消'
  }
  if (record.medicalstate) {
    return '已完成'
  }
  return '预约成功'
}

// 获取状态类型
const getStatusType = (record: AppointmentRecord) => {
  if (record.reason && record.cancelTime) {
    return 'default'
  }
  if (record.medicalstate) {
    return 'default'
  }
  return 'primary'
}

// 获取状态颜色
const getStatusColor = (record: AppointmentRecord) => {
  if (record.reason && record.cancelTime) {
    return '#969799'
  }
  if (record.medicalstate) {
    return '#969799'
  }
  return '#1989fa'
}

// 方法
const goBack = () => {
  router.back()
}

const selectPatient = (patient: Patient) => {
  selectedPatient.value = patient
  showPatientList.value = false
  // 重新加载预约记录
  appointmentRecords.value = []
  finished.value = false
  loadAppointmentRecords()
}

const loadAppointmentRecords = async () => {
  if (!selectedPatient.value || loading.value) return
  
  loading.value = true
  try {
    const response = await api.getAppointmentRecordsByPatient(selectedPatient.value.patientId)
    if (response.data) {
      appointmentRecords.value = [...appointmentRecords.value, ...response.data]
      finished.value = true // 假设一次性加载所有数据
    }
  } catch (error) {
    console.error('获取预约记录失败:', error)
  } finally {
    loading.value = false
  }
}

const goToAppointmentDetails = (record: AppointmentRecord) => {
  router.push({
    name: 'appointment-record-details',
    params: { appointmentId: record.appointmentId.toString() }
  })
}

const onTimeConfirm = (value: Date) => {
  selectedDate.value = value
  timeFilter.value = 'custom'
  showTimePicker.value = false
  // 重新加载数据
  appointmentRecords.value = []
  finished.value = false
  loadAppointmentRecords()
}

const loadPatients = async () => {
  try {
    const response = await api.getPatients()
    if (response.data) {
      patients.value = response.data
      // 默认选择第一个就诊人
      if (patients.value.length > 0 && patients.value[0]) {
        selectedPatient.value = patients.value[0]
        loadAppointmentRecords()
      }
    }
  } catch (error) {
    console.error('获取就诊人列表失败:', error)
  }
}

onMounted(() => {
  loadPatients()
})
</script>

<style scoped>
.appointment-records-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.patient-card {
  margin: 16px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.patient-info {
  flex: 1;
}

.patient-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.patient-card-number {
  font-size: 14px;
  color: #646566;
}

.switch-patient {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1989fa;
  font-size: 14px;
  cursor: pointer;
}

.filter-section {
  margin: 0 16px 16px;
  display: flex;
  gap: 12px;
}

.appointment-records {
  margin: 0 16px;
}

.appointment-record-card {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.record-info {
  flex: 1;
}

.department-doctor {
  font-size: 15px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.consultation-department {
  font-size: 14px;
  color: #646566;
  margin-bottom: 4px;
}

.consultation-time {
  font-size: 14px;
  color: #646566;
  margin-bottom: 4px;
}

.patient-name {
  font-size: 13px;
  color: #969799;
}

.status {
  margin-left: 12px;
}

.patient-list-popup {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebedf0;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}
</style>

